<template>
	<view class="graybg">
		<view class="rrcard">
			<view class="box address">
				<image src="/static/navigation.png"></image>
				<view class="text">
					<view class="top">{{order.userName}},{{order.moblie}}</view>
					<view>{{order.orderAttrb}}</view>
				</view>
			</view>
		</view>
		<view class="rrcard">
			<view class="box">
				<view class="billItem">
					<view>订单状态： <text>{{order.dealStatus==1?'未付款':order.dealStatus==2?'待发货':'已发货'}}</text></view>
					<view>订单编号： <text>{{order.orderId}}</text></view>
					<view >下单时间： <text>{{order.createTime}}</text></view>
					<!-- <view>预订人： <text>{{order.orderUserName}}</text></view>
					<view>手机号： <text>{{order.orderUserPhone}}</text></view>
					<view>性别： <text>{{order.orderUserSex=='0'?'男':'女'}}</text></view> -->
				</view>
			</view>
		</view>
		<view class="rrcard">
			<view class="t">商品信息</view>
			<view class="box topBox">
				<image :src="order.orderAttra"></image>
				<view class="textBox">
					<text class="title">{{order.orderAttrb}}</text>
					<text class="disc">数量 {{order.payCount}}</text>
					<text class="price">{{order.remarks}}</text>
				</view>
			</view>
		</view>
        <view class="rrcard">
        	<view class="t">价格信息</view>
        	<view class="box">
        		<view class="billItem">
    <!--    			<view class="flex">
        					<text>会员权益：</text>
        			
        					<view>
        						<text class="originPrice" >￥{{order.price}}</text>
        						<text  style="line-height:70rpx">￥{{params.price*params.ifHotsale}}</text>
        					</view>
        				
        			</view>
        			<view class="flex">
        					<text>优惠券：</text>
        					<view>{{params.waterName?'-￥'+params.waterPrice:"选择优惠券"}}</view>
        				</view> -->
        				<view class="flex">
        					<text>合计：</text>
        					<text class="price">￥{{order.reallyPrice}}</text>
        				</view>
        		</view>
        	</view>
        </view>
		<view class="payBtnBox" v-if="order.dealStatus==1">
			<view class="cancelBtn" @click="payCancel">取消订单</view>
			<view class="payBtn" @click="pay()">立即支付
				<uni-countdown style="display: inline-block;" color="#fff" splitorColor="#fff" @timeup="timeup"
					:show-day="false" :show-hour="false" :minute="15" :second="0"></uni-countdown>
			</view>
		</view>
		<view class="payBtnBox"  v-if="order.dealStatus==1">
			<view class="payBtn" style="width: 100%;" @click="pay()">立即支付
				<uni-countdown style="display: inline-block;" color="#fff" splitorColor="#fff" @timeup="timeup"
					:show-day="false" :show-hour="false" :start="countdown.start" :minute="countdown.minute"
					:second="countdown.second"></uni-countdown>
			</view>
		</view>

		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="info" cancelText="取消" confirmText="确定" content="是否确认支付？" @confirm="dialogConfirm" 
				@close="dialogClose"></uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="alertPayOk" type="dialog">
			<uni-popup-dialog type="success" confirmText="查看订单详情" content="支付成功" @confirm="goBillDetail"  @close="goBillDetail">
			</uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="alertPayWrong" type="dialog">
			<uni-popup-dialog type="error" confirmText="查看订单详情" content="支付失败" @confirm="goBillDetail" @close="goBillDetail">
			</uni-popup-dialog>
		</uni-popup>

	</view>

</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import * as api from '@/common/api.js';
	import _ from 'lodash'
	import {
		ref,
		getCurrentInstance
	} from 'vue';
	import dayjs from 'dayjs'
	import {
		getCurrUser
	} from '../../common/login';


	const {
		proxy
	} = getCurrentInstance()

	const vTypeImg = ref('/static/v1.png');
	const items = ref(['消费记录', '充值记录']);
	const current = ref(0);
	const isPay = ref(false);
	const lockPay = ref(false);
	const isClick = ref(false);
	const alertDialog = ref(null);
	const alertPayOk = ref(null);
	const alertPayWrong = ref(null);
	const currUser = ref({});
	const orderId = ref('');
	const order = ref({});
	const orderFrom = ref(0);
	const orderInfo = ref([]);
	const myBalance = ref(0);
	const form = ref({
		payType: 1
	});
	const countdown = ref({
		start: false,
		minute: 0,
		second: 0
	})
	onLoad((option) => {
		orderId.value=option
		init()
	})
     function init(){
		  uni.showLoading({
		  			title: '加载中'
		  		});
		  		api.listorderlistbyselectinfo({orderId:orderId.value.orderId}).then(res => {
		  			uni.hideLoading();
		  			 order.value = res.extend.list[0]
		  			 
		  		        if(order.value.dealStatus==1){
							 let leftTime = dayjs(res.extend.list[0].createTime).add(30, 'minute').valueOf() - dayjs().valueOf()
							 if (leftTime > 0) {
							 	countdown.value = {
							 		start: true,
							 		minute: Math.floor(leftTime / 1000 / 60),
							 		second: Math.ceil(leftTime / 1000) % 60
							 	}
							 } else {
							 	countdown.value = {
							 		start: true
							 	}
							 	timeup()
							 }
						}
		  			
		  			// }else{
		  			// 	countdown.value = {
		  			// 		start: true
		  			// 	}
		  			// }
		  
		  		})
		  currUser.value = uni.getStorageSync('currUser')
	 }
	function payChange(evt) {
		form.value.payType = evt.detail.value
	}

	function pay(n) {
		if(lockPay.value == true){
			return
		}else{
			lockPay.value = true
		}
		alertDialog.value.open()
	}

	let timeHandle = null;

	function dialogConfirm() {
		// console.log(isClick.value)
		if(isClick.value == true){
			return
		} else {
			isClick.value = true
			uni.showLoading({
				title: '支付中...'
			});
			goPayForOrder()
		}
	}

	function goPayForOrder() {
	
		const nowOpenId = uni.getStorageSync('nowOpenId');
		api.wxjsapipaytest({orderid:order.value.orderId,userid:currUser.value.userid,openId:nowOpenId}).then(resp=>{
	 
			isClick.value = false
			if (resp.extend.JSAPIbean) {
				// console.log('weipay')
				wePay(resp.extend.JSAPIbean)
			}
		}).catch(() => {
				alertPayWrong.value.open()
		}).finally(() => {
				uni.hideLoading()
				timeHandle = setTimeout(() => {
					goBillDetail()
				}, 3000)
		})
	}


	function wePay(configdata) {
		// console.log(configdata)
		// 微信支付
		uni.requestPayment({
			"provider": "wxpay",
			// "appId": configdata.appid,
			"timeStamp": configdata.timestamp, // 时间戳（单位：秒）
			"nonceStr": configdata.nonceStr,
			"package": configdata.packageinfo, // 随机字符串
			"signType": 'MD5', // 签名，这里用的 MD5/RSA 签名
			"paySign": configdata.paySign,
			success(res) {
				alertPayOk.value.open()
				  // subscribe()
				// api.maPayConfirmCourse({
				// 	orderId:order.value.orderId,
				// 	successFlag:true
				// }).then((res)=>{
				// 	lockPay.value = false
				// })
			},
			fail(e) {
				console.log(e)
				uni.showToast({
					title: '支付取消',
					icon: 'none',
					duration: 2000
				})
				// api.maPayConfirmCourse({
				// 	orderId:order.value.id,
				// 	successFlag:false
				// }).then((res)=>{
				// 	lockPay.value = false
				// })

			}
		})
	}

	function payCancel() {
		console.log(123)
		uni.showModal({
			title: '提示',
			content: '确定取消订单吗',
			success: function(res) {
				if (res.confirm) {
					// const eventChannel = proxy.getOpenerEventChannel()
					api.courseCancelOrder(orderId.value).then((res) => {
						 uni.navigateBack()
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	function dialogClose() {
		alertDialog.value.close()
		lockPay.value = false
	}

	function goBillDetail() {
		if (timeHandle) {
			clearTimeout(timeHandle)
		}
		// uni.redirectTo({
		// 	url: `/pages/usercenter/recoverOrderDetail?id=${orderId.value}`
		// })
		init()
	}

	function timeup() {
		if (countdown.value.start) {
			// 自动取消订单
			uni.showModal({
				title: '提示',
				content: '订单支付已超时',
				showCancel: false,
				success: function(res) {
					if (res.confirm) {
						// api.courseCancelOrder(orderId.value).then((res) => {
						// 	uni.navigateBack()
						// })
						uni.redirectTo({
							url: `/pages/usercenter/recoveryList`
						})
					}
				}
			})
		}
	}

	// 订阅
	function subscribe() {
		// 场馆预订成功通知 订场取消提醒 订单退款通知
		uni.requestSubscribeMessage({
			tmplIds: ['qFlUhr7oq4SvEVL59bcy9eI5eb-3ciImCSp0GL6SRMI'],
			success: (res) => {
				console.log('success:', res)
			}
		})
	}

</script>

<style lang="scss" scoped>
	.flex{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.billItem {
		width: auto;

		.uni-input {
			padding: 15rpx 0;
			color: #000;
		}

		.trInput {
			text-align: right;
			float: right;
		}
	}

	.rrcard .box {
		padding: 0 0 1px;
		margin: 20rpx 0 0;
	}

	.graybg {
		background: #f7f8fa;
		height: 100vh;
		width: 100vw;
		overflow: auto;
	}

	.whitebg {
		background: #fff;
		margin-top: 15rpx;
		border-radius: 20rpx;
		margin-bottom: 180rpx;
	}

	.payBtnBox {
		width: 750rpx;
		line-height: 90rpx;
		position: fixed;
		bottom: 0;
		display: flex;
		height: 120rpx;
	}

	.cancelBtn {
		background: #fff;
		font-size: 28rpx;
		color: #999;
		text-align: center;
		width: 40%;
	}

	.payBtn {
		background: #FF8124;
		text-align: center;
		color: #FFFFFF;
		width: 60%;
		font-size: 36rpx;
	}

	.uni-list-cell::after {
		display: none;
	}

	.littleimgBox {
		display: flex;
		align-items: center;
	}

	.littleimg {
		width: 50rpx;
		height: 50rpx;
		margin-right: 15rpx;
	}

	.billItem .price {
		font-weight: bold;
		font-size: 45rpx;
		color: #ff8124;
	}

	.originPrice {
		line-height: 70rpx;
		margin: 0 0 0 6rpx;
		color: #999;
		text-decoration: line-through;
	}
	.topBox{
		display: flex;
		padding:30rpx!important;
		image{
			width:220rpx;
			height:220rpx;
		}
		.textBox{
			box-sizing: border-box;
			padding: 10rpx;;
			flex:1;
			margin-left:20rpx;
			display: flex;
			height:220rpx;
			flex-direction: column;
			// justify-content: space-between;
			.title{
				font-size:16px;
				font-weight: bold;
			}
			.price{
				 font-size:12px;
			}
			.disc{
				display: -webkit-box;
				  -webkit-line-clamp: 2;
				  -webkit-box-orient: vertical;
				  overflow: hidden;
				  text-overflow: ellipsis;
				  font-size:12px;
			}
		}
	}
	.address{
		padding:20rpx!important;
		font-size:14px;
		display: flex;
	justify-content: flex-start;
	image{
		width:50px;
		height:50px;
	}
	.text{
		flex:1;
		padding-left:20rpx;
	}
	}
</style>
